package giit.computerbase.util;


/**
 * This class is for check file's header in order to judge file's type<br>
 * User: tum0r
 * Package Name: tum0r.file
 * Time: 2018/10/28 Sunday 22:12:34
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class CheckFile {
    public static final String $_CLASS = "CAFE BABE";
    public static final String $_ZIP = "504B 0304";
    public static final String $_RAR = "5261 7221";
    public static final String $_7Z = "377A BCAF";
    public static final String $_JPG = "FFD8 FF";
    public static final String $_PNG = "8950 4E47";

    public static boolean check(String path, String flag) throws IOException {
        return check(new File(path), flag);
    }

    public static boolean check(File file, String flag) throws IOException {
        if (flag != null && !flag.equals("")) {
            int length = flag.length() / 2;
            String temp;
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] header = new byte[length];
            fileInputStream.read(header, 0, header.length);
            fileInputStream.close();
            StringBuffer result = new StringBuffer();
            for (int index = 0; index < length; index++) {
                temp = Integer.toHexString(header[index] & 0xFF).toUpperCase();
                if (temp.length() == 1) {
                    result.append("0");
                }
                result.append(temp);
            }
            return result.toString().equals(flag.toUpperCase().replace(" ", ""));
        }
        return false;
    }
}
